<template>
  <div class="internal-production-detail-container">
    <el-container>
      <el-header class="detail-header">
        <div class="header-content">
          <div class="page-title">
            <el-button 
              :icon="ArrowLeft" 
              @click="goBack" 
              circle 
              style="margin-right: 15px;"
            />
            内部生产详情
          </div>
          <div class="header-actions">
            <el-button type="primary" :icon="Edit" @click="handleEdit">编辑</el-button>
            <el-button :icon="Printer" @click="handlePrint">打印</el-button>
          </div>
        </div>
      </el-header>
      
      <el-main class="detail-main" v-loading="loading">
        <!-- 基础信息 -->
        <div class="info-section">
          <div class="section-title">◆ 基础信息</div>
          <div class="info-grid">
            <div class="info-item">
              <label>生产主题：</label>
              <span>{{ productionDetail.productionInfo?.productionSubject || '-' }}</span>
            </div>
            <div class="info-item">
              <label>生产类型：</label>
              <span>{{ productionDetail.productionInfo?.productionType || '-' }}</span>
            </div>
            <div class="info-item">
              <label>生产单号：</label>
              <span>{{ productionDetail.productionInfo?.productionOrderNo || '-' }}</span>
            </div>
            <div class="info-item">
              <label>销售订单：</label>
              <span>{{ productionDetail.productionInfo?.salesOrderHold || '-' }}</span>
            </div>
            <div class="info-item">
              <label>截止日期：</label>
              <span>{{ formatDate(productionDetail.productionInfo?.documentDate) }}</span>
            </div>
            <div class="info-item">
              <label>关联项目：</label>
              <span>{{ productionDetail.productionInfo?.associatedProject || '-' }}</span>
            </div>
            <div class="info-item">
              <label>发起部门：</label>
              <span>{{ productionDetail.productionInfo?.initiatingDepartment || '-' }}</span>
            </div>
            <div class="info-item">
              <label>负责人：</label>
              <span>{{ productionDetail.productionInfo?.responsiblePerson || '-' }}</span>
            </div>
            <div class="info-item">
              <label>联系电话：</label>
              <span>{{ productionDetail.productionInfo?.contactPhone || '-' }}</span>
            </div>
            <div class="info-item">
              <label>生产部门：</label>
              <span>{{ productionDetail.productionInfo?.productionDepartment || '-' }}</span>
            </div>
            <div class="info-item">
              <label>生产人员：</label>
              <span>{{ productionDetail.productionInfo?.productionPersonnel || '-' }}</span>
            </div>
            <div class="info-item">
              <label>创建人：</label>
              <span>{{ productionDetail.productionInfo?.createName || '-' }}</span>
            </div>
            <div class="info-item">
              <label>创建时间：</label>
              <span>{{ formatDateTime(productionDetail.productionInfo?.createTime) }}</span>
            </div>
            <div class="info-item">
              <label>修改人：</label>
              <span>{{ productionDetail.productionInfo?.modifierName || '-' }}</span>
            </div>
            <div class="info-item">
              <label>修改时间：</label>
              <span>{{ formatDateTime(productionDetail.productionInfo?.modifyTime) }}</span>
            </div>
            <div class="info-item full-width">
              <label>备注：</label>
              <span>{{ productionDetail.productionInfo?.remarks || '-' }}</span>
            </div>
          </div>
        </div>

        <!-- 生产产品 -->
        <div class="info-section">
          <div class="section-title">◆ 生产产品</div>
          <el-table 
            :data="productionDetail.productionItems || []" 
            class="detail-table" 
            :border="true"
            :stripe="true">
            <el-table-column type="index" label="序号" width="80px" align="center"/>
            <el-table-column prop="itemName" label="物品名称" min-width="150px"/>
            <el-table-column prop="specification" label="规格" width="150px"/>
            <el-table-column prop="unit" label="单位" width="80px" align="center"/>
            <el-table-column prop="brand" label="品牌" width="120px"/>
            <el-table-column prop="plannedProduction" label="计划生产数量" width="130px" align="center"/>
            <el-table-column prop="remark" label="备注" min-width="150px"/>
          </el-table>
          <div v-if="!productionDetail.productionItems || productionDetail.productionItems.length === 0" class="no-data">
            暂无生产产品数据
          </div>
        </div>

        <!-- 消耗物品 -->
        <div class="info-section">
          <div class="section-title">◆ 消耗物品</div>
          <el-table 
            :data="productionDetail.consumableItems || []" 
            class="detail-table" 
            :border="true"
            :stripe="true">
            <el-table-column type="index" label="序号" width="80px" align="center"/>
            <el-table-column prop="itemName" label="物品名称" min-width="150px"/>
            <el-table-column prop="warehouseId" label="仓库" width="100px"/>
            <el-table-column prop="unit" label="单位" width="80px" align="center"/>
            <el-table-column prop="brand" label="品牌" width="120px"/>
            <el-table-column prop="warehouseName" label="仓库名称" width="120px"/>
            <el-table-column prop="plannedQuantity" label="计划数量" width="100px" align="center"/>
            <el-table-column prop="number" label="编号" width="100px"/>
            <el-table-column prop="remark" label="备注" min-width="150px"/>
          </el-table>
          <div v-if="!productionDetail.consumableItems || productionDetail.consumableItems.length === 0" class="no-data">
            暂无消耗物品数据
          </div>
        </div>

        <!-- 附件 -->
        <div class="info-section">
          <div class="section-title">◆ 附件</div>
          <div class="attachment-list">
            <div 
              v-for="(attachment, index) in productionDetail.attachments || []" 
              :key="index" 
              class="attachment-item"
            >
              <div class="attachment-info">
                <h4>{{ attachment.filename || attachment.name || '未知文件' }}</h4>
                <p>文件大小：{{ formatFileSize(attachment.filesize || 0) }}</p>
                <p>上传时间：{{ formatDateTime(attachment.uploadtime) }}</p>
                <p>上传人：{{ attachment.uploadPerson || '-' }}</p>
              </div>
              <div class="attachment-actions">
                <el-button link type="primary" @click="handlePreview(attachment)">查看</el-button>
                <el-button link type="primary" @click="handleDownload(attachment)">下载</el-button>
              </div>
            </div>
            <div v-if="!productionDetail.attachments || productionDetail.attachments.length === 0" class="no-attachment">
              暂无附件
            </div>
          </div>
        </div>

        <!-- 操作记录 -->
        <div class="info-section">
          <div class="section-title">◆ 操作记录</div>
          <el-table 
            :data="productionDetail.operationRecords || []" 
            class="detail-table" 
            :border="true"
            :stripe="true">
            <el-table-column type="index" label="序号" width="80px" align="center"/>
            <el-table-column prop="operationName" label="操作名称" width="150px"/>
            <el-table-column prop="operationTime" label="操作时间" width="160px" align="center">
              <template #default="scope">
                {{ formatDateTime(scope.row.operationTime) }}
              </template>
            </el-table-column>
            <el-table-column prop="operationContent" label="操作内容" min-width="200px"/>
            <el-table-column prop="operationType" label="操作类型" width="100px" align="center"/>
            <el-table-column prop="beforeStatus" label="操作前状态" width="120px"/>
            <el-table-column prop="afterStatus" label="操作后状态" width="120px"/>
            <el-table-column prop="ipAddress" label="IP地址" width="130px"/>
            <el-table-column prop="remarks" label="备注" min-width="150px"/>
          </el-table>
          <div v-if="!productionDetail.operationRecords || productionDetail.operationRecords.length === 0" class="no-data">
            暂无操作记录
          </div>
        </div>

        <!-- 关闭按钮 -->
        <div class="bottom-actions">
          <el-button @click="goBack">关闭</el-button>
        </div>
      </el-main>
    </el-container>
  </div>
</template>

<script lang="ts" setup>
import { getInternalProductionDetailById } from '@/Https/server';
import { onMounted, ref } from 'vue';
import { ElMessage } from 'element-plus'
import { ArrowLeft, Edit, Printer } from '@element-plus/icons-vue'
import { useRouter, useRoute } from 'vue-router'

const router = useRouter();
const route = useRoute();

// 加载状态
const loading = ref(false);

// 内部生产详情数据
const productionDetail = ref<any>({});

// 获取路由参数中的生产ID
const productionId = ref(route.params.id as string);

onMounted(() => {
  if (productionId.value) {
    loadProductionDetail();
  } else {
    ElMessage.error('内部生产ID参数缺失');
  }
});

// 加载内部生产详情数据
const loadProductionDetail = async () => {
  if (!productionId.value || productionId.value <= 0) {
    ElMessage.error('内部生产ID无效');
    return;
  }
  
  try {
    loading.value = true;
    console.log('开始加载内部生产详情数据...', 'ID:', productionId.value);
    
    const response: any = await getInternalProductionDetailById({ productionId: productionId.value });
    console.log('内部生产详情API响应:', response);
    
    if (response && response.code === 200 && response.data) {
      productionDetail.value = response.data;
      console.log('内部生产详情数据:', productionDetail.value);
    } else {
      ElMessage.error(response?.message || '获取内部生产详情失败');
    }
  } catch (error: any) {
    console.error('获取内部生产详情失败:', error);
    ElMessage.error(error?.message || '获取内部生产详情失败，请稍后重试');
  } finally {
    loading.value = false;
  }
};

// 格式化日期
const formatDate = (dateStr: string) => {
  if (!dateStr) return '-';
  const date = new Date(dateStr);
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
};

// 格式化日期时间
const formatDateTime = (dateString: string) => {
  if (!dateString) return '-';
  const date = new Date(dateString);
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  });
};

// 格式化文件大小
const formatFileSize = (bytes: number) => {
  if (bytes === 0) return '0 bytes';
  const k = 1024;
  const sizes = ['bytes', 'KB', 'MB', 'GB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
};

// 编辑按钮
const handleEdit = () => {
  router.push(`/internal-production/edit/${productionId.value}`);
};

// 打印按钮
const handlePrint = () => {
  ElMessage.info('打印功能待开发');
};

// 返回按钮
const goBack = () => {
  router.back();
};

// 预览附件
const handlePreview = (attachment: any) => {
  if (attachment.filepath) {
    window.open(attachment.filepath, '_blank');
  } else {
    ElMessage.info('暂无预览地址');
  }
};

// 下载附件
const handleDownload = (attachment: any) => {
  if (attachment.filepath) {
    const link = document.createElement('a');
    link.href = attachment.filepath;
    link.download = attachment.filename || 'download';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  } else {
    ElMessage.info('暂无下载地址');
  }
};
</script>

<style scoped>
.internal-production-detail-container {
  background: #f5f5f5;
  height: 100vh;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
}

.detail-header {
  background: white;
  border-bottom: 1px solid #e6e6e6;
  height: 80px !important;
  padding: 0 20px;
  flex-shrink: 0;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 100%;
}

.page-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  display: flex;
  align-items: center;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 10px;
}

.detail-main {
  background: white;
  margin: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  padding: 30px;
  flex: 1;
  overflow-y: auto;
  max-height: calc(100vh - 120px);
}

.info-section {
  margin-bottom: 40px;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 20px;
  border-left: 4px solid #409EFF;
  padding-left: 10px;
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 20px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
}

.info-item {
  display: flex;
  align-items: center;
}

.info-item.full-width {
  grid-column: 1 / -1;
  align-items: flex-start;
}

.info-item label {
  font-weight: 600;
  color: #606266;
  min-width: 100px;
  margin-right: 10px;
}

.info-item span {
  color: #303133;
  word-break: break-all;
}

.detail-table {
  width: 100%;
  margin-top: 10px;
}

.no-data, .no-attachment {
  text-align: center;
  padding: 40px 20px;
  color: #909399;
  background: #f8f9fa;
  border-radius: 8px;
  margin-top: 10px;
}

.attachment-list {
  margin-top: 10px;
}

.attachment-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  border: 1px solid #e6e6e6;
  border-radius: 8px;
  margin-bottom: 10px;
  background: #f8f9fa;
}

.attachment-info h4 {
  margin: 0 0 5px 0;
  color: #303133;
  font-size: 14px;
}

.attachment-info p {
  margin: 2px 0;
  color: #909399;
  font-size: 12px;
}

.attachment-actions {
  display: flex;
  gap: 10px;
}

.bottom-actions {
  text-align: center;
  margin-top: 40px;
  padding-top: 20px;
  border-top: 1px solid #e6e6e6;
}

:deep(.el-button--text) {
  padding: 4px 8px;
}

:deep(.el-table .el-table__cell) {
  padding: 8px 0;
}
</style> 